package com.siyuanren.gcocp.facade.impl;

import com.alibaba.fastjson.JSON;
import com.siyuanren.gcocp.common.web.bean.Token;
import com.siyuanren.gcocp.consts.GcocpConsts;
import com.siyuanren.gcocp.consts.RedisConsts;
import com.siyuanren.gcocp.facade.JedisFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.*;

//import com.siyuanren.gcocp.geetest.GeetestLib;

/**
 * Created by   guwr
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.facade.impl.JedisFacadeImpl
 * Date         2017/6/19
 * Time         11:07
 * Description
 *
 * @author guwr
 */
@Component
public class JedisFacadeImpl implements JedisFacade {

    private static Logger logger = LoggerFactory.getLogger(JedisFacadeImpl.class);

    //    @Autowired
    private JedisCluster jedisCluster;


    public static void main(String[] args) {
//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");
//        JedisCluster jedisCluster = context.getBean("jedisCluster", JedisCluster.class);
//        System.out.println("jedisCluster = " + jedisCluster);
//        Long zadd1 = jedisCluster.zadd("score", 230, "zhangsan");
//        Long zadd2 = jedisCluster.zadd("score", 240, "lisi");
//        Long zadd3 = jedisCluster.zadd("score", 250, "wangwu");
//        Long zadd4 = jedisCluster.zadd("score", 100, "liuli");
//
//        Set<String> score = jedisCluster.zrange("score", 0, -1);
//        System.out.println("score = " + score);
//        Set<Tuple> score1 = jedisCluster.zrangeWithScores("score", 0, -1);
//        System.out.println("score1 = " + JSON.toJSONString(score1));
//        Long score2 = jedisCluster.zcount("score", 230, 240);
//        System.out.println("score2 = " + score2);
//        Set<String> score3 = jedisCluster.zrevrange("score", 0, -1);
//        System.out.println("score3 = " + score3);

//        Long hset = jedisCluster.hset("hget", "filed1", "hello");
//
//        System.out.println("hget = " + hset);
    }


    /**
     * 删除所有KEY
     *
     * @param jedisCluster
     */
    private void delAllKey(JedisCluster jedisCluster) {
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        Set<String> keys = new HashSet<>();
        List<String> delKeys = new ArrayList<>();
        for (String s : delKeys) {
            for (String k : clusterNodes.keySet()) {
                logger.debug("Getting keys from: {}", k);
                JedisPool jp = clusterNodes.get(k);
                Jedis connection = jp.getResource();
                try {
                    keys.addAll(connection.keys(s + "*"));
                } catch (Exception e) {
                    logger.error("Getting keys error: {}", e);
                } finally {
                    logger.debug("Connection closed.");
                    connection.close();//用完一定要close这个链接！！！
                }
            }
            logger.debug("Keys gotten!");
        }
        keys.forEach(o -> jedisCluster.del(o));
    }

    @Override
    public Set<String> delByPattern(String pattern) {
        logger.info("pattern = [" + pattern + "]");
        Set<String> keys = getByPattern(pattern);
        keys.forEach(o -> jedisCluster.del(o));
        return keys;
    }

    @Override
    public Set<String> getByPattern(String pattern) {
        logger.info("pattern = [" + pattern + "]");
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        Set<String> keys = new HashSet<>();
        for (Map.Entry<String, JedisPool> entry : clusterNodes.entrySet()) {
            JedisPool pool = entry.getValue();
            Jedis resource = pool.getResource();
            Set<String> stringSet = resource.keys(pattern);
            keys.addAll(stringSet);
        }
        return keys;
    }


    @Override
    public Long hset(String key, String field, String value) {
        return jedisCluster.hset(key, field, value);
    }

    @Override
    public String hget(String key, String field) {
        return jedisCluster.hget(key, field);
    }

    @Override
    public Long hdel(String key, String field) {
        return null;
    }

    @Override
    public Boolean hexists(String key, String field) {
        return null;
    }

    @Override
    public String setex(String key, int seconds, String value) {
        return jedisCluster.setex(key, seconds, value);
    }

    @Override
    public Long setnx(String key, String value) {
        return jedisCluster.setnx(key, value);
    }

    @Override
    public Long del(String key) {
        return jedisCluster.del(key);
    }

    @Override
    public Long zrem(String key, String member) {
        return jedisCluster.zrem(key, member);
    }

    @Override
    public String get(String key) {
        return jedisCluster.get(key);
    }

    @Override
    public String set(String key, String value) {
        return jedisCluster.set(key, value);
    }

    @Override
    public Long sadd(String key, String member) {
        return jedisCluster.sadd(key, member);
    }

    @Override
    public Boolean sismember(String key, String member) {
        return jedisCluster.sismember(key, member);
    }

    @Override
    public Set<String> zrange(String seatKey, long start, long end) {
        return jedisCluster.zrange(seatKey, start, end);
    }

    @Override
    public Long zcard(String key) {
        return jedisCluster.zcard(key);
    }

    @Override
    public Set<String> zrangeByScore(String key, double min, double max) {
        return jedisCluster.zrangeByScore(key, min, max);
    }

    @Override
    public void zadd(String key, double score, String member) {
        jedisCluster.zadd(key, score, member);
    }

    @Override
    public Boolean exists(String key) {
        return null;
    }

    @Override
    public Long expire(String key, int seconds) {
        return jedisCluster.expire(key, seconds);
    }


    @Override
    public boolean tokenExist(String token) {
        // 登录token
        String tokenKey = RedisConsts.TOKEN + token;
        Boolean exists = jedisCluster.exists(tokenKey);
        if (exists) {
            jedisCluster.expire(tokenKey, GcocpConsts.LOGIN_TOKEN_TIME_OUT);
            return true;
        }
        return false;
    }

    @Override
    public Token getByToken(String token) {
        String tokenKey = RedisConsts.TOKEN + token;
        String loginUser = jedisCluster.get(tokenKey);
        Token dto = JSON.parseObject(loginUser, Token.class);
        return dto;
    }

    @Override
    public void logOut(String token) {
        logger.info("logOut,token={}", token);
        jedisCluster.del(RedisConsts.TOKEN + token);
    }

}
